<template>
  <div class="activity-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">活动管理</h1>
        <p class="page-subtitle">管理所有校园活动，审核、发布和监控活动状态</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="exportData" :loading="exporting">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.total }}</div>
              <div class="stat-label">总活动数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon pending">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.pending }}</div>
              <div class="stat-label">待审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon published">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.published }}</div>
              <div class="stat-label">已发布</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon today">
              <el-icon><Plus /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.today }}</div>
              <div class="stat-label">今日新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="活动名称">
          <el-input
            v-model="filterForm.keyword"
            placeholder="请输入活动名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="活动类型">
          <el-select v-model="filterForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="学术讲座" value="lecture" />
            <el-option label="文艺演出" value="performance" />
            <el-option label="体育竞技" value="sports" />
            <el-option label="社会实践" value="practice" />
            <el-option label="志愿服务" value="volunteer" />
            <el-option label="技能培训" value="training" />
            <el-option label="社团活动" value="club" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="草稿" value="draft" />
            <el-option label="待审核" value="pending" />
            <el-option label="已发布" value="published" />
            <el-option label="已结束" value="ended" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="组织者">
          <el-input
            v-model="filterForm.organizer"
            placeholder="请输入组织者"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchActivities">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card class="table-card">
      <!-- 批量操作 -->
      <div class="table-header">
        <div class="batch-actions">
          <el-button
            type="success"
            :disabled="!selectedActivities.length"
            @click="batchApprove"
          >
            批量通过
          </el-button>
          <el-button
            type="warning"
            :disabled="!selectedActivities.length"
            @click="batchReject"
          >
            批量拒绝
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedActivities.length"
            @click="batchDelete"
          >
            批量删除
          </el-button>
        </div>
        
        <div class="table-info">
          <span>共 {{ pagination.total }} 条记录</span>
        </div>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="activities"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="title" label="活动名称" min-width="200">
          <template #default="{ row }">
            <div class="activity-title">
              <el-link type="primary" @click="viewActivity(row)">
                {{ row.title }}
              </el-link>
              <div class="activity-tags">
                <el-tag
                  v-for="tag in row.tags"
                  :key="tag"
                  size="small"
                  style="margin-right: 4px; margin-top: 4px;"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">{{ getTypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="organizer" label="组织者" width="120">
          <template #default="{ row }">
            <div class="organizer-info">
              <div>{{ row.organizer?.name }}</div>
              <div class="organizer-org">{{ row.organizer?.organization }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="startTime" label="开始时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="location" label="地点" width="150" show-overflow-tooltip />
        
        <el-table-column prop="participants" label="报名情况" width="120">
          <template #default="{ row }">
            <div class="participants-info">
              <div>{{ row.currentParticipants || 0 }}/{{ row.maxParticipants }}</div>
              <el-progress
                :percentage="getParticipationRate(row)"
                :stroke-width="4"
                :show-text="false"
                style="margin-top: 4px;"
              />
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button link type="primary" @click="viewActivity(row)">
                查看
              </el-button>
              
              <el-button
                v-if="row.status === 'pending'"
                link
                type="success"
                @click="approveActivity(row)"
              >
                通过
              </el-button>
              
              <el-button
                v-if="row.status === 'pending'"
                link
                type="warning"
                @click="rejectActivity(row)"
              >
                拒绝
              </el-button>
              
              <el-button
                v-if="['published', 'pending'].includes(row.status)"
                link
                type="info"
                @click="cancelActivity(row)"
              >
                取消
              </el-button>
              
              <el-button
                link
                type="danger"
                @click="deleteActivity(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 活动详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="活动详情"
      width="80%"
      :before-close="handleDetailClose"
    >
      <div v-if="currentActivity" class="activity-detail">
        <div class="detail-header">
          <h2>{{ currentActivity.title }}</h2>
          <el-tag :type="getStatusType(currentActivity.status)">
            {{ getStatusText(currentActivity.status) }}
          </el-tag>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-section">
              <h4>基本信息</h4>
              <p><strong>类型：</strong>{{ getTypeText(currentActivity.type) }}</p>
              <p><strong>组织者：</strong>{{ currentActivity.organizer?.name }} ({{ currentActivity.organizer?.organization }})</p>
              <p><strong>联系人：</strong>{{ currentActivity.contactPerson }}</p>
              <p><strong>联系电话：</strong>{{ currentActivity.contactPhone }}</p>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="detail-section">
              <h4>时间地点</h4>
              <p><strong>开始时间：</strong>{{ formatDateTime(currentActivity.startTime) }}</p>
              <p><strong>结束时间：</strong>{{ formatDateTime(currentActivity.endTime) }}</p>
              <p><strong>活动地点：</strong>{{ currentActivity.location }}</p>
            </div>
          </el-col>
        </el-row>
        
        <div class="detail-section">
          <h4>活动描述</h4>
          <p>{{ currentActivity.description }}</p>
        </div>
        
        <div class="detail-section" v-if="currentActivity.requirements">
          <h4>报名要求</h4>
          <p>{{ currentActivity.requirements }}</p>
        </div>
        
        <div class="detail-section">
          <h4>报名信息</h4>
          <p><strong>报名人数：</strong>{{ currentActivity.currentParticipants || 0 }}/{{ currentActivity.maxParticipants }}</p>
          <p><strong>报名时间：</strong>{{ formatDateTime(currentActivity.registrationStart) }} 至 {{ formatDateTime(currentActivity.registrationEnd) }}</p>
        </div>
        
        <div class="detail-section" v-if="currentActivity.tags?.length">
          <h4>活动标签</h4>
          <el-tag
            v-for="tag in currentActivity.tags"
            :key="tag"
            style="margin-right: 8px;"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button
            v-if="currentActivity?.status === 'pending'"
            type="success"
            @click="approveActivity(currentActivity)"
          >
            通过审核
          </el-button>
          <el-button
            v-if="currentActivity?.status === 'pending'"
            type="warning"
            @click="rejectActivity(currentActivity)"
          >
            拒绝审核
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Calendar,
  Clock,
  Check,
  Plus,
  Download
} from '@element-plus/icons-vue'
import api from '@/utils/api'
import { formatDateTime } from '@/utils/date'

const loading = ref(false)
const exporting = ref(false)
const detailVisible = ref(false)
const currentActivity = ref(null)
const selectedActivities = ref([])
const activities = ref([])

const stats = reactive({
  total: 0,
  pending: 0,
  published: 0,
  today: 0
})

const filterForm = reactive({
  keyword: '',
  type: '',
  status: '',
  organizer: '',
  dateRange: []
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const loadStats = async () => {
  try {
    const response = await api.get('/admin/activities/stats')
    Object.assign(stats, response.data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadActivities = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...filterForm
    }
    
    if (filterForm.dateRange?.length === 2) {
      params.startDate = filterForm.dateRange[0]
      params.endDate = filterForm.dateRange[1]
    }
    
    const response = await api.get('/admin/activities', { params })
    activities.value = response.data.list || []
    pagination.total = response.data.total || 0
    
  } catch (error) {
    ElMessage.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

const searchActivities = () => {
  pagination.page = 1
  loadActivities()
}

const resetFilter = () => {
  Object.assign(filterForm, {
    keyword: '',
    type: '',
    status: '',
    organizer: '',
    dateRange: []
  })
  searchActivities()
}

const handleSelectionChange = (selection) => {
  selectedActivities.value = selection
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadActivities()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadActivities()
}

const viewActivity = (activity) => {
  currentActivity.value = activity
  detailVisible.value = true
}

const handleDetailClose = () => {
  detailVisible.value = false
  currentActivity.value = null
}

const approveActivity = async (activity) => {
  try {
    await ElMessageBox.confirm('确认通过该活动的审核？', '确认操作', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await api.put(`/admin/activities/${activity.id}/approve`)
    ElMessage.success('活动审核通过')
    
    loadActivities()
    loadStats()
    
    if (detailVisible.value) {
      detailVisible.value = false
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败，请重试')
    }
  }
}

const rejectActivity = async (activity) => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入拒绝理由', '拒绝审核', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入拒绝理由',
      inputValidator: (value) => {
        if (!value || value.trim() === '') {
          return '请输入拒绝理由'
        }
        return true
      }
    })
    
    await api.put(`/admin/activities/${activity.id}/reject`, { reason })
    ElMessage.success('活动审核已拒绝')
    
    loadActivities()
    loadStats()
    
    if (detailVisible.value) {
      detailVisible.value = false
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败，请重试')
    }
  }
}

const cancelActivity = async (activity) => {
  try {
    await ElMessageBox.confirm('确认取消该活动？取消后将无法恢复。', '确认操作', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await api.put(`/admin/activities/${activity.id}/cancel`)
    ElMessage.success('活动已取消')
    
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败，请重试')
    }
  }
}

const deleteActivity = async (activity) => {
  try {
    await ElMessageBox.confirm('确认删除该活动？删除后将无法恢复。', '确认删除', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'danger'
    })
    
    await api.delete(`/admin/activities/${activity.id}`)
    ElMessage.success('活动已删除')
    
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请重试')
    }
  }
}

const batchApprove = async () => {
  try {
    await ElMessageBox.confirm(`确认批量通过 ${selectedActivities.value.length} 个活动的审核？`, '批量操作', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedActivities.value.map(item => item.id)
    await api.put('/admin/activities/batch-approve', { ids })
    
    ElMessage.success('批量审核通过成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败，请重试')
    }
  }
}

const batchReject = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入拒绝理由', '批量拒绝', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入拒绝理由',
      inputValidator: (value) => {
        if (!value || value.trim() === '') {
          return '请输入拒绝理由'
        }
        return true
      }
    })
    
    const ids = selectedActivities.value.map(item => item.id)
    await api.put('/admin/activities/batch-reject', { ids, reason })
    
    ElMessage.success('批量拒绝成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败，请重试')
    }
  }
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确认批量删除 ${selectedActivities.value.length} 个活动？删除后将无法恢复。`, '批量删除', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'danger'
    })
    
    const ids = selectedActivities.value.map(item => item.id)
    await api.delete('/admin/activities/batch-delete', { data: { ids } })
    
    ElMessage.success('批量删除成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败，请重试')
    }
  }
}

const exportData = async () => {
  try {
    exporting.value = true
    
    const params = { ...filterForm }
    if (filterForm.dateRange?.length === 2) {
      params.startDate = filterForm.dateRange[0]
      params.endDate = filterForm.dateRange[1]
    }
    
    const response = await api.get('/admin/activities/export', {
      params,
      responseType: 'blob'
    })
    
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `活动数据_${new Date().toISOString().slice(0, 10)}.xlsx`
    link.click()
    
    window.URL.revokeObjectURL(url)
    ElMessage.success('数据导出成功')
    
  } catch (error) {
    ElMessage.error('数据导出失败')
  } finally {
    exporting.value = false
  }
}

const getStatusType = (status) => {
  const statusMap = {
    draft: 'info',
    pending: 'warning',
    published: 'success',
    ended: 'info',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    draft: '草稿',
    pending: '待审核',
    published: '已发布',
    ended: '已结束',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getTypeColor = (type) => {
  const typeMap = {
    lecture: 'primary',
    performance: 'success',
    sports: 'warning',
    practice: 'info',
    volunteer: 'success',
    training: 'primary',
    club: 'warning',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

const getTypeText = (type) => {
  const typeMap = {
    lecture: '学术讲座',
    performance: '文艺演出',
    sports: '体育竞技',
    practice: '社会实践',
    volunteer: '志愿服务',
    training: '技能培训',
    club: '社团活动',
    other: '其他'
  }
  return typeMap[type] || type
}

const getParticipationRate = (activity) => {
  if (!activity.maxParticipants) return 0
  return Math.round(((activity.currentParticipants || 0) / activity.maxParticipants) * 100)
}

onMounted(() => {
  loadStats()
  loadActivities()
})
</script>

<style scoped>
.activity-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.pending {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.published {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.today {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.filter-card {
  margin-bottom: 24px;
}

.table-card {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.batch-actions {
  display: flex;
  gap: 8px;
}

.table-info {
  color: #909399;
  font-size: 14px;
}

.activity-title {
  max-width: 200px;
}

.activity-tags {
  margin-top: 4px;
}

.organizer-info {
  line-height: 1.4;
}

.organizer-org {
  font-size: 12px;
  color: #909399;
}

.participants-info {
  text-align: center;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.activity-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.detail-header h2 {
  margin: 0;
  color: #303133;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  color: #409eff;
  font-weight: 600;
}

.detail-section p {
  margin: 8px 0;
  line-height: 1.6;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .activity-management {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .stats-cards .el-col {
    margin-bottom: 16px;
  }
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .batch-actions {
    width: 100%;
    flex-wrap: wrap;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table tr:hover td) {
  background-color: #f8f9fa;
}
</style>